package com.heyu.cgsd.ui.activity;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.heyu.cgsd.R;
import com.heyu.cgsd.base.BaseActivity;
import com.heyu.cgsd.db.DataDBHelper;
import com.heyu.cgsd.model.bean.CurrencyBean;
import com.heyu.cgsd.model.http.OKHttp;
import com.heyu.cgsd.ui.adapter.BaseRVAdapter;
import com.heyu.cgsd.ui.dialog.CustomDialog;
import com.heyu.cgsd.util.DateTimeUtils;
import com.heyu.cgsd.util.ExchangeUtils;
import com.heyu.cgsd.util.SharePreferenceUtils;
import com.heyu.cgsd.util.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汇率转换
 */
public class ExchangeActivity extends BaseActivity {
    private TextView tv_title;
    private ImageView iv_return;
    private LinearLayout ll_sp_1, ll_sp_2, ll_sp_3;
    private TextView tv_sp_1, tv_sp_2, tv_sp_3;
    private int sp_pos_1, sp_pos_2, sp_pos_3;

    private TextView num_1, num_2, num_3, unit_1, unit_2, unit_3;
    private float[] rates;

    private List<Object[]> objectList;

    private TextView kb_num_0, kb_num_1, kb_num_2, kb_num_3, kb_num_4, kb_num_5, kb_num_6, kb_num_7, kb_num_8, kb_num_9, kb_num_dot, kb_num_ac;
    private LinearLayout kb_num_del;
    private DataDBHelper testDBHelper;

    @org.jetbrains.annotations.Nullable
    @Override
    protected Integer getContentView() {
        setTitleBackground(BG_BLACK);
        return R.layout.activity_exchange;
    }

    @Override
    public void initView() {
        tv_title = findViewById(R.id.tv_title);
        iv_return = findViewById(R.id.img_back);

        ll_sp_1 = findViewById(R.id.ll_sp_1);
        ll_sp_2 = findViewById(R.id.ll_sp_2);
        ll_sp_3 = findViewById(R.id.ll_sp_3);

        tv_sp_1 = findViewById(R.id.tv_sp_1);
        tv_sp_2 = findViewById(R.id.tv_sp_2);
        tv_sp_3 = findViewById(R.id.tv_sp_3);

        num_1 = findViewById(R.id.num_1);
        num_2 = findViewById(R.id.num_2);
        num_3 = findViewById(R.id.num_3);

        unit_1 = findViewById(R.id.unit_1);
        unit_2 = findViewById(R.id.unit_2);
        unit_3 = findViewById(R.id.unit_3);

        kb_num_0 = findViewById(R.id.kb_num_0);
        kb_num_1 = findViewById(R.id.kb_num_1);
        kb_num_2 = findViewById(R.id.kb_num_2);
        kb_num_3 = findViewById(R.id.kb_num_3);
        kb_num_4 = findViewById(R.id.kb_num_4);
        kb_num_5 = findViewById(R.id.kb_num_5);
        kb_num_6 = findViewById(R.id.kb_num_6);
        kb_num_7 = findViewById(R.id.kb_num_7);
        kb_num_8 = findViewById(R.id.kb_num_8);
        kb_num_9 = findViewById(R.id.kb_num_9);
        kb_num_dot = findViewById(R.id.kb_num_dot);
        kb_num_del = findViewById(R.id.kb_num_del);
        kb_num_ac = findViewById(R.id.kb_num_ac);

    }

    public void initData() {
        tv_title.setText("汇率转换");
        objectList = new ArrayList<>();

        testDBHelper = DataDBHelper.getInstance(ExchangeActivity.this);
        List<Map> maps = testDBHelper.queryListMap("select * from currency where rates <> '0.0'", null);
        int len = maps.size();
        String[] titles = new String[len];
        String[] units = new String[len];
        rates = new float[len];
        for (int i = 0; i < len; i++) {
            titles[i] = (String) maps.get(i).get("titles");
            units[i] = (String) maps.get(i).get("units");
            rates[i] = Float.valueOf(String.valueOf(maps.get(i).get("rates")));
            Object[] o = {titles[i], units[i]};
            objectList.add(o);
        }

        sp_pos_1 = 0;
        sp_pos_2 = 1;
        sp_pos_3 = 2;

        tv_sp_1.setText((String) (objectList.get(0))[1]);
        tv_sp_2.setText((String) (objectList.get(1))[1]);
        tv_sp_3.setText((String) (objectList.get(2))[1]);

        unit_1.setText(titles[0]);
        unit_2.setText(titles[1]);
        unit_3.setText(titles[2]);

        startConvert();
        // 更新汇率
        updateData();
        initListener();
    }

    protected void initListener() {
        iv_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ll_sp_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDialog(1);
            }
        });

        ll_sp_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDialog(2);
            }
        });

        ll_sp_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDialog(3);
            }
        });

        setKeyBoardListener();

        num_1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                startConvert();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void setKeyBoardListener() {
        kb_num_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('0');
            }
        });

        kb_num_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('1');
            }
        });

        kb_num_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('2');
            }
        });

        kb_num_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('3');
            }
        });

        kb_num_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('4');
            }
        });

        kb_num_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('5');
            }
        });

        kb_num_6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('6');
            }
        });

        kb_num_7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('7');
            }
        });

        kb_num_8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('8');
            }
        });

        kb_num_9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('9');
            }
        });

        kb_num_dot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                formatInput('.');
            }
        });

        kb_num_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = StringUtils.replaceSeparate(num_1.getText().toString());
                if (!str.equals("0")) {
                    str = str.substring(0, str.length() - 1);
                    if (str.equals("")) {
                        str = "0";
                    }
                }
                formatNum(str);
            }
        });

        kb_num_ac.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num_1.setText("0");
                num_2.setText("0");
                num_3.setText("0");
            }
        });
    }

    private void formatInput(char input) {
        String str = StringUtils.replaceSeparate(num_1.getText().toString());

        if (input >= '0' && input <= '9') {
            if ((str.contains(".") && str.length() < 20) || (!str.contains(".") && str.length() < 15)) {
                if (str.equals("0")) {
                    str = String.valueOf(input);
                } else {
                    str += String.valueOf(input);
                }
                formatNum(str);
            }
        } else if (input == '.') {
            if (!str.contains(".") && str.length() < 15) {
                str += ".";
                formatNum(str);
            }
        }
    }


    private void formatNum(String str) {
        num_1.setText(StringUtils.formatInteger(str));
    }

    private void startConvert() {
        String str = StringUtils.replaceSeparate(num_1.getText().toString());
        double result = Double.valueOf(str) * rates[sp_pos_1];

        double result2 = result / rates[sp_pos_2];
        double result3 = result / rates[sp_pos_3];

        num_2.setText(StringUtils.formatToSeparate4Exchange(String.valueOf(result2)));
        num_3.setText(StringUtils.formatToSeparate4Exchange(String.valueOf(result3)));
    }

    private void showCustomDialog(final int type) {
        View view = getLayoutInflater().inflate(R.layout.dialog_spinner, null);
        final CustomDialog customDialog = new CustomDialog(this, 0, 0, view, R.style.DialogTheme);
        TextView tv_dialog_title = view.findViewById(R.id.tv_dialog_title);
        RecyclerView rv_list = view.findViewById(R.id.rv_list);
        TextView cancel = view.findViewById(R.id.tv_dialog_cancel);

        tv_dialog_title.setText("选择币种");

        BaseRVAdapter rvAdapter = new BaseRVAdapter<Object[]>(objectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_spinner;
            }

            @Override
            public void convert(VH holder, Object[] data, int position) {
                holder.setText(R.id.item_spinner_name, (String) data[0]);
                holder.setText(R.id.item_spinner_unit, (String) data[1]);
            }
        };

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ExchangeActivity.this);

        rv_list.setLayoutManager(linearLayoutManager);
        rv_list.setAdapter(rvAdapter);

        if (rv_list.getItemDecorationCount() <= 0) {
            rv_list.addItemDecoration(new DividerItemDecoration(ExchangeActivity.this, DividerItemDecoration.VERTICAL));
        }

        rvAdapter.setOnItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type == 1) {
                    sp_pos_1 = position;
                    unit_1.setText((String) (objectList.get(position))[0]);
                    tv_sp_1.setText((String) (objectList.get(position))[1]);
                } else if (type == 2) {
                    sp_pos_2 = position;
                    unit_2.setText((String) (objectList.get(position))[0]);
                    tv_sp_2.setText((String) (objectList.get(position))[1]);
                } else if (type == 3) {
                    sp_pos_3 = position;
                    unit_3.setText((String) (objectList.get(position))[0]);
                    tv_sp_3.setText((String) (objectList.get(position))[1]);
                }
                startConvert();
                customDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.dismiss();
            }
        });

        customDialog.show();
        customDialog.setCanceledOnTouchOutside(true);
    }

    private void updateData() {
        DateFormat dateFormat = SimpleDateFormat.getDateInstance();
        String nowStr = dateFormat.format(new Date());
        int cha = DateTimeUtils.daysBetween(nowStr, SharePreferenceUtils.getString(this, "now"));
        if (cha >= 2) {
            if (isNetworkConnected(getApplicationContext())) {
//                    Log.e("AAA", "update rates");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ExchangeUtils.getExchange();
                        int len = ExchangeUtils.titles.length;
                        for (int i = 1; i < len; i++) {
                            int count = testDBHelper.rawQuery("select count(*) from currency where titles = '" + ExchangeUtils.titles[i] + "'", null);
//                        Log.e("AAA", "count=" + count);
//                        Log.e("AAA", "index=" + i);
                            if (count == 0) {
                                testDBHelper.insert("currency", new String[]{"titles", "units", "rates"}, new String[]{ExchangeUtils.titles[i], ExchangeUtils.units[i], "0.0"});
                            } else {
                                OKHttp.getCurrency(ExchangeUtils.units[i], ExchangeUtils.units[0], new OKHttp.IDataListener() {
                                    @Override
                                    public void onSuccess(String data) {
                                        Gson gson = new Gson();
//                                        Log.e("AAA", isError(data) + "");
                                        if (!isError(data)) {
                                            CurrencyBean currencyBean = gson.fromJson(data, CurrencyBean.class);
                                            List<CurrencyBean.ResultBean> resultBeanList = currencyBean.getResult();
                                            if (resultBeanList != null) {
                                                Map<String, Object> columnValues = new HashMap<>();
                                                Map<String, String> whereParams = new HashMap<>();
                                                columnValues.put("rates", resultBeanList.get(0).getExchange());

                                                whereParams.put("units", resultBeanList.get(0).getCurrencyF());
                                                testDBHelper.update("currency", columnValues, whereParams);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure() {
                                        Log.e("AAA", "获取汇率失败了");
                                    }
                                });
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }).start();
            }
        }
    }

    /**
     * 手机是否联网
     */
    private boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isConnected();//有网
            }
        }
        return false;//没有网
    }

    public boolean isError(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            int errCode = jsonObject.getInt("error_code");
            if (errCode == 0) {
                return false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return true;
    }

}
